<template>
  <div class="customCom_v">
    <div style="width: 100%;height: 25%;display: flex;justify-content: space-between">
      <BlockBox width="49%">
        <template #title>render函数使用</template>
        <template #content>
          <html-content></html-content>
          <tem-com style="color: red" v-model:num.three="countNum" v-model:age.double = age></tem-com>
        </template>
      </BlockBox>
      <BlockBox width="48%">
        <template #title>单表单项校验多项</template>
        <template #content>
          <el-form :model="formModel"
                   :rules="formRules"
                   class="elForm"
                   ref="formRef"
                   label-width="60px"
                   label-position="left"
                   size="default">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formModel.name"></el-input>
            </el-form-item>
            <div class="line_form_item">
              <el-form-item label="别称" prop="alternative_name">
                <el-input v-model="formModel.alternative_name"></el-input>
              </el-form-item>
              <el-form-item label="全称" prop="full_name">
                <el-input v-model="formModel.full_name"></el-input>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" @click="submitForm('form')">立即创建</el-button>
              <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
          </el-form>
        </template>
      </BlockBox>
    </div>
    <BlockBox width="100%" height="40%">
      <template #title>wangEditor 案例</template>
      <template #content>
        <WangEditor></WangEditor>
      </template>
    </BlockBox>
    <BlockBox width="100%" height="30%">
      <template #title>CSS文字溢出显示省略号,且出现el-tooltip(单行/多行)</template>
      <template #content>
        <div style="display: flex">
          <div style="width: 50%">
            1.px 格式
            <BeyondWidthTip width="250px" text="px 格式-->CSS文字溢出显示省略号,且出现el-tooltip"></BeyondWidthTip>
            2.% 格式
            <BeyondWidthTip  width="80%" text="% 格式-->CSS文字溢出显示省略号,且出现el-tooltip"></BeyondWidthTip>
            3.tip 宽度换行 px
            <BeyondWidthTip width="80%" wrapWidth="200px" text="tip(px)宽度超出自定义的宽度进行换行-->CSS文字溢出显示省略号,且出现el-tooltip"></BeyondWidthTip>
            4.tip 宽度换行  %
            <BeyondWidthTip width="80%" wrapWidth="50%" text="tip(%)宽度超出自定义的宽度进行换行-->CSS文字溢出显示省略号,且出现el-tooltip"></BeyondWidthTip>
          </div>
          <div style="width: 50%">
            <div class="outer_box">
              <div class="text_info" @mouseenter="handleMouse">
                <el-tooltip class="item" effect="dark" placement="top-start" :disabled="disabledTip">
                  <template #content>
                    <div style="width: 300px">
                      {{message_overflow}}
                    </div>
                  </template>
                  <span>{{message_overflow}}</span>
                </el-tooltip>
              </div>
            </div>
            <div class="outer_box" style="margin-top: 20px">
              <div class="text_info" @mouseenter="handleMouse">
                <el-tooltip class="item" effect="dark" placement="top-start" :disabled="disabledTip">
                  <template #content>
                    <div style="width: 300px">
                      {{message1}}
                    </div>
                  </template>
                  <span>{{message1}}</span>
                </el-tooltip>
              </div>
            </div>
            <br>
            <p>tooltip中添加点击事件（将事件绑到window上）</p>
            <BeyondWidthTip width="80%" wrapWidth="200px" :htmlText="long_tip"></BeyondWidthTip>
          </div>
        </div>
      </template>
    </BlockBox>
  </div>
</template>

<script>
import {h} from "vue";
import {ElButton} from "element-plus";

const temCom = {
  props: {
    num: {
      type: Number,
      default: 1
    },
    age: {
      type: Number,
      default: 27
    },
    numModifiers: {
      default: () => {}
    },
    ageModifiers: {
      default: () => {}
    }
  },
  template: `
    <div>{{ $attrs }}</div>
    <div :style="$attrs.style">{{ num }}</div>
    <div>{{age}}</div>
    <button @click="updateCountNum">自增</button>
  `,
  methods: {
    updateCountNum: function () {
      this.$emit('update:num', this.numModifiers.three && this.num * 3 || (this.num + 1))
      this.$emit('update:age', this.ageModifiers.double && this.age * 2)
    }
  }
}
const htmlContent = {
  render: function () {
    return h("div", {className: "app"}, [
      h("h3", {className: "title"}, "render标题"),
      h("p", null, "render内容"),
      h(ElButton, // 组件名称
          {
            type: 'success', // 组件属性
            onClick: () => {
              alert('点击了按钮')
            },
          },
          {
            default: () => 'Click me'
          } // 组件内容
      ),
    ])
  }
}
</script>

<script setup>
import BlockBox from "@/components/BlockBox";
import BeyondWidthTip from "../../components/BeyondWidthTip";
import { h, onMounted, onUnmounted, ref} from "vue";
import { formatDate } from '@/untils/untils.js'
import WangEditor from "./CustomCom/WangEditor";
import {ElMessage, ElButton} from "element-plus";
import {useGlobalProperties} from "../../hooks/globalVar.js";
let {DeploymentAddress} = useGlobalProperties()

const user = JSON.parse(localStorage.getItem('user'))
let countNum = ref(1)
let age = ref(27)

let formRef = ref(null)
let formModel = ref({
  name: '',
  alternative_name: '',
  full_name: '',
  groups: []
})
let formRules = ref({
  name: [{ required: true, message: 'Input name', trigger: 'blur' }],
  alternative_name: [{ required: true, message: 'Input alternative_name', trigger: 'blur' }],
  full_name: [{ required: true, message: 'Input full_name', trigger: 'blur' }]
})

const submitForm = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.warn('校验失败，失败项：', fields)
    }
  })
}
const resetForm = () => {
  formRef.value.resetFields()
}

// WebSocket
let wsRef = ref(null)
let webSocketInfo = ref([])
function WebSocketTest() {
  let params = {
    opType: "chat",
    account: user.account
  }
  let paramsString = new URLSearchParams(params).toString()
  webSocketInfo.value = []
  if ("WebSocket" in window) {
    let socketUrl = process?.env?.NODE_ENV === 'development' ? ("ws://127.0.0.1:6789?" + paramsString) : (`ws://${DeploymentAddress}:6789?` + paramsString)
    // 打开一个 web socket
    wsRef.value = new WebSocket(socketUrl);
    wsRef.value.onopen = function () {
      let msg = 'WebSocket测试连接：' + formatDate(new Date())
      // Web Socket 已连接上，使用 send() 方法发送数据
      let postMsg = {
        account: user.account,
        time: $('#nowTime')[0].innerHTML,
        message: msg
      }
      wsRef.value.send(JSON.stringify(postMsg));
    };
    wsRef.value.onmessage = function (evt) {
      webSocketInfo.value = webSocketInfo.value.concat(eval(evt.data))
    };
    wsRef.value.onclose = function () {
      // 关闭 websocket
      webSocketInfo.value.push("连接已关闭...")
    };
  }
  else {
    // 浏览器不支持 WebSocket
    ElMessage.error("您的浏览器不支持 WebSocket!");
  }
}
function closeWebSocket() {
  wsRef.value.close()
}

let worker = ref(null);
let message = ref('Hello Worker');
// 创建并初始化worker
worker.value = new Worker(new URL('@/workers/mainWorker.js', import.meta.url));
// 发送消息到worker
function sendMessageToWorker() {
  worker.value.postMessage({message: message.value});
  worker.value.onmessage = (e) => {
    message.value = e.data
    console.log('收到来自worker的消息，Received message from worker:', e.data);
  }
}

let httpWorker = ref(null)
let httpWorkerMessage = ref('httpWorkerMessage')
let httpLoading = ref(false)
httpWorker.value = new Worker(new URL('@/workers/httpWorker.js', import.meta.url))
function sendHttpWorker() {
  httpLoading.value = true
  httpWorker.value.postMessage({message: 'message'})
  httpWorker.value.onmessage = (e) => {
    httpWorkerMessage.value = e.data
    httpLoading.value = false
  }
}

let message_overflow = ref('这里是一段可能会超长的文本内容，需要显示为超出3行时用省示完整内容。这里是一段可能')
let message1 = ref('这里是一段可能会超长的文本内容，需要显示为超出3行时用省示完整内容。')
let disabledTip = ref(true)
const long_tip = '<span style="color: red;cursor: pointer" onclick="viewList()">查看同步文件列表</span>,这里是一段可能会超长的文本内容，需要显示为超出3行时用省示完整内容。'
function viewList() {
  console.log('后端使用html绑定事件，<span style="color: red;cursor: pointer" onclick="viewList()">查看同步文件列表</span>,这里是一段可能会超长的文本内容，需要显示为超出3行时用省示完整内容。')
}
function handleMouse(e){
  disabledTip.value = !(e.target.clientHeight < e.target.scrollHeight)
}

function terminate() {
  if (httpWorker.value) {
    httpWorker.value.terminate()
    httpWorker.value = null
  }
  if (worker.value) {
    worker.value.terminate()
    worker.value = null
  }
}

onMounted(() => {
  window.viewList = viewList
})
onUnmounted(() => {
  window.viewList = null
  terminate()
})
</script>

<style scoped lang="less">

.customCom_v {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.line_form_item {
  display: flex;
  justify-content: space-between;
  .el-form-item {
    width: 45%;
  }
}
.elForm {

}
.outer_box {
  width: 300px;
  height: 60px;
  padding: 10px 8px;
  line-height: 20px;
  background-color: #F2F6FC;
}
.text_info{
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;/*省略几行写几*/
  -webkit-box-orient: vertical;
}
</style>